import {defineStore} from "pinia";
import {currRoute, queryToUrl} from "@/utils";
import {PM_ROUTE_PATH} from "@/stores/pm";

type RouteHistoryState = {
  routeHistory: string[]
  isBackRoute: boolean
}

export const useRouteHistoryStore = defineStore('RouteHistory', {
  state: (): RouteHistoryState => ({
    routeHistory: [],
    isBackRoute: false,
  }),
  actions: {
    routeHistoryAdd(url: string, query: Record<string, string> = {}) {
      // 路由返回操作不记入历史
      if (this.isBackRoute) {
        this.isBackRoute = false
        return;
      }
      const newUrl = queryToUrl(url, query);
      if (this.routeHistory.length > 0) {
        const len = this.routeHistory.length;
        const lastRoute = this.routeHistory[len - 1];
        if (newUrl === lastRoute) {
          return;
        }
      }
      this.routeHistory.push(newUrl);
      if (this.routeHistory.length > 20) {
        const len = this.routeHistory.length;
        this.routeHistory = this.routeHistory.slice(len - 20, len);
      }
    },
    routeGoBack() {
      this.isBackRoute = true
      const cRoute = currRoute();
      if (this.routeHistory.length > 1) {
        const len = this.routeHistory.length;
        const lastRoute = this.routeHistory[len - 2];
        this.routeHistory = this.routeHistory.slice(0, len - 1);
        uni.navigateTo({ url: lastRoute });
      } else if (cRoute.path.includes(PM_ROUTE_PATH)) {
        uni.redirectTo({url: `${PM_ROUTE_PATH}/index/index`})
      } else {
        uni.redirectTo({url: '/pages/index/index'})
      }
    }
  },
  // persist: true,
})
